package com.nova.bluetooth.xunFeiSDK.mainFunction;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.nova.bluetooth.R;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupEngine;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupListener;
import com.nova.bluetooth.xunFeiSDK.recorder.AudioRecorder;
import com.nova.bluetooth.xunFeiSDK.recorder.RecorderFactory;
import com.nova.bluetooth.xunFeiSDK.utils.CopyAssetsUtils;


public class WakeupActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = WakeupActivity.class.getSimpleName();
    int wakeCount = 0;
    Handler handler = new Handler();
    private TextView mResText;
    private ScrollView mScrollView;
    // 多麦克算法库
    private WakeupEngine wakeupEngine;
    private AudioRecorder recorder;

    /**
     * 唤醒回调
     */
    private WakeupListener wakeupListener = new WakeupListener() {
        @Override
        public void onWakeup(int angle, int beam, int score, String keyWord) {
            wakeCount++;
            setText("唤醒成功,angle:" + angle + " beam:" + beam + " score=" + score);
            setText("唤醒词" + keyWord);
            setText("唤醒次数：" + wakeCount);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asr);
        initLayout();
        // 资源拷贝
        CopyAssetsUtils.portingFile(this);
    }

    private void initLayout() {
        findViewById(R.id.init_sdk).setOnClickListener(this);
        findViewById(R.id.btnStartRecord).setOnClickListener(this);
        findViewById(R.id.btnStopRecord).setOnClickListener(this);
        findViewById(R.id.btnSave).setOnClickListener(this);
        ((TextView) findViewById(R.id.myTitle)).setText("CAE(降噪+唤醒）");
        ((Button) findViewById(R.id.btnStopRecord)).setText("停止录音");
        mScrollView = findViewById(R.id.scrollView);
        mResText = findViewById(R.id.res_text);
        mResText.append("默认唤醒词：小飞小飞\n");
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.init_sdk) {
            initSDK();
        } else if (id == R.id.btnStartRecord) {
            startRecord();
        } else if (id == R.id.btnStopRecord) {
            stopRecord();
        }

    }

    private void initSDK() {
        //状态初始化
        EngineConstants.isRecording = false;
        //TODO 开发者需要实现生成sn的代码，参考：https://www.yuque.com/iflyaiui/zzoolv/tgftb5
        //注意事项1: sn每台设备需要唯一！！！！WakeupEngine的sn和AIUI的sn要一致
        //注意事项2: 获取的值要保持稳定，否则会重复授权，浪费授权量
        EngineConstants.serialNumber = "iflytek-test";
        Log.i(TAG, "sn : " + EngineConstants.serialNumber);
        //初始化CAE(降噪+唤醒)
        wakeupEngine = WakeupEngine.getInstance(wakeupListener);
        if (wakeupEngine != null) {
            setText("CAE初始化成功");
        } else {
            setText("CAE初始化失败");
        }

        //初始化录音
        if (recorder == null) {
            recorder= RecorderFactory.getRecorder();
        }

        if (recorder != null) {
            setText("录音机初始化成功");
        } else {
            setText("录音机初始化失败");
        }
    }


    private void startRecord() {
        if (recorder != null) {
            int ret = recorder.startRecord();
            if (0 == ret) {
                setText("开启录音成功！");
            } else if (111111 == ret) {
                setText("异常,AlsaRecorder is null ...");
            } else {
                setText("开启录音失败，请查看/dev/snd/下的设备节点是否有777权限！\nAndroid 8.0 以上需要暂时使用setenforce 0 命令关闭Selinux权限！");
                destroyRecord();
            }
        }
    }

    private void stopRecord() {
        if (recorder != null) {
            recorder.stopRecord();
            setText("停止录音");
        }
    }


    private void destroyRecord() {
        stopRecord();
        recorder = null;
        Log.d(TAG, "destroy is Done!");
    }

    //根据scrollView 和子view去测量滑动的位置
    private void scrollToBottom(final ScrollView scrollView, final View view) {
        handler.post(() -> {
            if (scrollView == null || view == null) {
                return;
            }
            // offset偏移量。是指当textview中内容超出 scrollview的高度，超出部分就是偏移量
            int offset = view.getMeasuredHeight()
                    - scrollView.getMeasuredHeight();
            if (offset < 0) {
                offset = 0;
            }
            //scrollview开始滚动
            scrollView.scrollTo(0, offset);
        });
    }

    //打印到屏幕
    private void setText(final String str) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            mResText.append(str + " \n");
            scrollToBottom(mScrollView, mResText);
        } else {
            runOnUiThread(() -> {
                mResText.append(str + " \n");
                scrollToBottom(mScrollView, mResText);
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EngineConstants.isRecording) {
            stopRecord();
        }
        if (recorder != null) {
            recorder.destroyRecord();
            recorder = null;
        }
        if (wakeupListener != null) {
            wakeupListener = null;
        }
        WakeupEngine.destroy();
    }
}